from PIL import Image
import io
import requests


# 获取图片信息
def get_img_mes(url):
    img_Mes = {}

    img = requests.request('get', url)
    infile = io.BytesIO(img.content)
    # 打开图片
    image = Image.open(infile)

    # 缩小图片，否则计算机压力太大
    small_image = image.resize((80, 80))
    result = small_image.convert(
        "P", palette=Image.ADAPTIVE, colors=10
    )

    # 10个主要颜色的图像

    # 找到主要的颜色
    palette = result.getpalette()
    color_counts = sorted(result.getcolors(), reverse=True)
    colors = list()

    for i in range(5):
        palette_index = color_counts[i][1]
        dominant_color = palette[palette_index * 3: palette_index * 3 + 3]
        colors.append(tuple(dominant_color))

    # 十六进制格式化颜色
    hex_colors = []
    for color in colors:

        r = '0x{:02X}'.format(color[0])
        g = '0x{:02X}'.format(color[1])
        b = '0x{:02X}'.format(color[2])
        hex_colors.append('#'+r[2:]+g[2:]+b[2:])
    img_Mes['colors'] = ','.join(hex_colors)
    # print(img_Mes['colors'])
    img_Mes['size'] = str(image.size[0])+'×'+str(image.size[1])

    return img_Mes


image_path = "https://tvax3.sinaimg.cn/large/006yt1Omgy1gphbsr1m6uj31kw1kw7wi.jpg"

# print(get_img_mes(image_path))
